package com.nl.lib_core.tool.extends

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData

/** 作者: wangfei 创建时间: 2021/9/1 包名: com.nl.lib_core.util.extends 类名: ViewExtends :View 转 bitmap */
fun View.view2Bitmap(): Bitmap {
  val ret = Bitmap.createBitmap(this.width, this.height, Bitmap.Config.ARGB_8888)
  val canvas = Canvas(ret)
  val bgDrawable = this.background
  bgDrawable?.draw(canvas) ?: canvas.drawColor(Color.WHITE)
  this.draw(canvas)
  return ret
}

fun <T> View.observe(liveData: LiveData<T>?, action: (T) -> Unit) {
  (context as? LifecycleOwner)?.let { owner -> liveData?.observe(owner, { action(it) }) }
}

// -----扩展属性-----

var View.bottomMargin: Int
  get(): Int {
    return (layoutParams as ViewGroup.MarginLayoutParams).bottomMargin
  }
  set(value) {
    (layoutParams as ViewGroup.MarginLayoutParams).bottomMargin = value
  }

var View.topMargin: Int
  get(): Int {
    return (layoutParams as ViewGroup.MarginLayoutParams).topMargin
  }
  set(value) {
    (layoutParams as ViewGroup.MarginLayoutParams).topMargin = value
  }

var View.rightMargin: Int
  get(): Int {
    return (layoutParams as ViewGroup.MarginLayoutParams).rightMargin
  }
  set(value) {
    (layoutParams as ViewGroup.MarginLayoutParams).rightMargin = value
  }

var View.leftMargin: Int
  get(): Int {
    return (layoutParams as ViewGroup.MarginLayoutParams).leftMargin
  }
  set(value) {
    (layoutParams as ViewGroup.MarginLayoutParams).leftMargin = value
  }

fun View?.gone() {
  this?.visibility = View.GONE
}

fun View?.visible() {
  this?.visibility = View.VISIBLE
}

fun View.inVisible() {
  visibility = View.INVISIBLE
}
